package com.gu.alipaytestboot.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.gu.alipaytestboot.config.AlipayConfig;
import com.gu.alipaytestboot.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.Gu
 * @date 2020/1/12 15:44
 * @function :  调用阿里支付
 **/
@CrossOrigin
@RestController
@RequestMapping("pay")
public class AliPayController {

    @Autowired private IdWorker idWorker;


    /**
     * 前台调用生成支付页面
     * @param amount  金额
     * @return
     */
    @RequestMapping("/createOrder")
    public String createOrder(String amount) {

        //使用IdWorker生成订单号
        String orderId = idWorker.nextId()+"";

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl,
                AlipayConfig.app_id,
                AlipayConfig.merchant_private_key,
                "json",
                AlipayConfig.charset,
                AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type
        );


        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(orderId);
        //付款金额，必填
        String total_amount = new String(amount);
        //订单名称，必填
        String subject = new String("测试");
        //商品描述，可空
        String body = new String("");

        Map<String,String> param = new HashMap<>();
        param.put("out_trade_no",out_trade_no);
        param.put("total_amount",total_amount);
        param.put("subject",subject);
        param.put("body",body);
        param.put("product_code","FAST_INSTANT_TRADE_PAY");


        String jsonString = JSON.toJSONString(param);
        alipayRequest.setBizContent(jsonString);

        //请求
        try {
            String response = alipayClient.pageExecute(alipayRequest).getBody();
            //System.out.println(response);
            return response;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return null;
    }

}
